package domain.client;

import domain.Commands;
import domain.GameSettings;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 *
 * @author Laurent Albessart
 * @version 31-dec-2011
 */
public class SundayThe19thGame implements ActionListener, WindowListener{

    private DatagramSocket datagramSocket;
    private JTextArea chatArea;
    private String name;
    private InetAddress ip;
    private int port;

    public SundayThe19thGame(String name, InetAddress ip, int port) {
        try {

            this.name = name;
            this.ip = ip;
            this.port = port;
            datagramSocket = new DatagramSocket();

            String msg = Commands.JOIN + GameSettings.SEPARATOR + name;
            byte[] msgBytes = msg.getBytes();

            DatagramPacket outPacket = new DatagramPacket(msgBytes, msgBytes.length, ip, port);

            //TODO make window with all components needed
            JFrame gameWindow = new JFrame("Sunday The 19th");
            gameWindow.setLayout(new BorderLayout());
            gameWindow.addWindowListener(this);

            chatArea = new JTextArea();
            chatArea.setEditable(false);
            
            JTextField chatInput = new JTextField();
            chatInput.addActionListener(this);

            gameWindow.add(new JScrollPane(chatArea), BorderLayout.CENTER);
            gameWindow.add(chatInput, BorderLayout.SOUTH);

            gameWindow.setSize(500, 400);
            gameWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            gameWindow.setVisible(true);

            datagramSocket.send(outPacket);

            System.out.println("thread to run made to receive messages");

            //Set up receiver thread!
            new Thread(new Runnable() {

                @Override
                public void run() {
                    System.out.println("running");
                    while (true) {
                        System.out.println("in true");
                        byte[] buffer = new byte[256];
                        DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);
                        try {
                            datagramSocket.receive(inPacket);
                            handleMessage(inPacket);
                        } catch (IOException ex) {
                            Logger.getLogger(SundayThe19thGame.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }).start();

        } catch (SocketException ex) {
            Logger.getLogger(SundayThe19thGame.class.getName()).log(Level.SEVERE, null, ex);
            //TODO error message "could not connect to server"
        } catch (IOException ex) {
            Logger.getLogger(SundayThe19thGame.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public void sendMessage(String msg) {
        try {
            byte[] msgBytes = msg.getBytes();

            DatagramPacket outPacket = new DatagramPacket(msgBytes, msgBytes.length, ip, port);
            
            datagramSocket.send(outPacket);
            
        } catch (IOException ex) {
            Logger.getLogger(SundayThe19thGame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void handleMessage(DatagramPacket inPacket) {
        String inMsg = new String(inPacket.getData(), 0, inPacket.getLength());
        //TODO do something with inMsg
        System.out.println("me, as client, got " + inMsg);
        String[] commands = inMsg.split(GameSettings.COMMANDSSPLIT);
        for (String msg : commands) {
            Commands command = Commands.valueOf(msg.substring(0, msg.indexOf(GameSettings.SEPARATOR)));
            String line = msg.substring(msg.indexOf(GameSettings.SEPARATOR) + 1);

            switch (command) {
                case TALK:
                    System.out.println(line);
                    chatArea.append("\n" + line);
                    break;
                default:
                    //unknown command -> handle!
                    System.out.println("unknown command: " + command);
                    break;
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        JTextField textField = (JTextField) ae.getSource();
        String msg = textField.getText();
        textField.setText(null);
        sendMessage(Commands.TALK + GameSettings.SEPARATOR + name + /*TODO enter chatverb*/ ": " + msg);
    }

    @Override
    public void windowOpened(WindowEvent we) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowClosing(WindowEvent we) {
        sendMessage(Commands.LEAVE + GameSettings.SEPARATOR + name);
        ((JFrame) we.getSource()).dispose();
    }

    @Override
    public void windowClosed(WindowEvent we) {
        /*sendMessage(Commands.LEAVE + GameSettings.SEPARATOR + name);
        ((JFrame) we.getSource()).dispose();*/
    }

    @Override
    public void windowIconified(WindowEvent we) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowDeiconified(WindowEvent we) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowActivated(WindowEvent we) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void windowDeactivated(WindowEvent we) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}
